/*
 * Copyright (C) 2020 original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package vip.justlive.easyproxy.server.web;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicReference;
import lombok.RequiredArgsConstructor;
import vip.justlive.easyproxy.core.context.Config;
import vip.justlive.easyproxy.core.context.Metrics;
import vip.justlive.easyproxy.server.entity.Client;
import vip.justlive.easyproxy.server.entity.Proxy;
import vip.justlive.easyproxy.server.repository.AdminRepository;
import vip.justlive.oxygen.core.config.ConfigFactory;
import vip.justlive.oxygen.core.config.ValueConfig;
import vip.justlive.oxygen.core.exception.Exceptions;
import vip.justlive.oxygen.core.net.http.HttpMethod;
import vip.justlive.oxygen.core.util.Resp;
import vip.justlive.oxygen.core.util.Strings;
import vip.justlive.oxygen.web.WebConf;
import vip.justlive.oxygen.web.annotation.Mapping;
import vip.justlive.oxygen.web.annotation.Param;
import vip.justlive.oxygen.web.annotation.PathParam;
import vip.justlive.oxygen.web.annotation.Router;
import vip.justlive.oxygen.web.hook.WebHook;
import vip.justlive.oxygen.web.http.Request;
import vip.justlive.oxygen.web.http.Response;
import vip.justlive.oxygen.web.result.Result;
import vip.justlive.oxygen.web.result.ViewResult;
import vip.justlive.oxygen.web.router.RoutingContext;

/**
 * http服务
 *
 * @author wubo
 */
@Router
@ValueConfig("easy-proxy.admin")
@RequiredArgsConstructor
public class WebRouter implements WebHook {

  private final Config config;
  private final AdminRepository repository;
  private final AtomicReference<String> token = new AtomicReference<>(UUID.randomUUID().toString());
  private final List<String> anons = Arrays.asList("/", "/login");


  @Mapping(value = "/", method = HttpMethod.GET)
  public ViewResult index() {
    if (checkLogin()) {
      return Result.view("/index.htm");
    }
    return Result.view("/login.htm");
  }

  @Mapping(value = "/login", method = HttpMethod.POST)
  public Resp login(@Param String username, @Param String password) {
    if (Objects.equals(config.getAdmin().getUsername(), username) && Objects
        .equals(config.getAdmin().getPassword(), password)) {
      String uid = UUID.randomUUID().toString();
      token.set(uid);
      Response.current().setCookie(Config.TOKEN, uid);
      return Resp.success();
    }
    return Resp.error("Username or password is error");
  }

  @Mapping(value = "/client", method = HttpMethod.GET)
  public Resp client() {
    return Resp.success(repository.clients());
  }

  @Mapping(value = "/client", method = HttpMethod.POST)
  public Resp saveClient(@Param String key, @Param String name) {
    repository.saveClient(key, name);
    return Resp.success();
  }

  @Mapping(value = "/client", method = HttpMethod.DELETE)
  public Resp deleteClient(@Param String keys) {
    for (String key : keys.split(Strings.COMMA)) {
      repository.deleteClient(key);
    }
    return Resp.success();
  }

  @Mapping(value = "/proxy/{key}", method = HttpMethod.GET)
  public Resp proxy(@PathParam String key) {
    Client client = repository.getClient(key);
    if (client == null) {
      return Resp.error("client not found");
    }
    return Resp.success(client.getProxies());
  }

  @Mapping(value = "/proxy/{key}", method = HttpMethod.POST)
  public Resp saveProxy(@PathParam String key, @Param Proxy proxy) {
    repository.saveProxy(key, proxy);
    return Resp.success();
  }

  @Mapping(value = "/proxy/{key}", method = HttpMethod.DELETE)
  public Resp deleteProxy(@PathParam String key, @Param String ids) {
    for (String id : ids.split(Strings.COMMA)) {
      repository.deleteProxy(key, Integer.parseInt(id));
    }
    return Resp.success();
  }

  @Mapping(value = "/metrics", method = HttpMethod.GET)
  public Resp metrics() {
    return Resp.success(Metrics.metrics());
  }

  @Override
  public boolean before(RoutingContext ctx) {
    String path = ctx.requestPath();
    boolean b = !path.startsWith(ConfigFactory.load(WebConf.class).getStaticPrefix())
        && !anons.contains(path) && !checkLogin();
    if (b) {
      throw Exceptions.fail("10000", "Not Login");
    }
    return true;
  }

  private boolean checkLogin() {
    return Objects.equals(token.get(), Request.current().getCookieValue(Config.TOKEN));
  }
}
